package cn.lyjuan.first.netty.demo._2_netty;

import cn.lyjuan.first.netty.demo._2_netty.selector.AbstractNIOSelector;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

/**
 * Worker工作选择器
 */
public class WorkerSelector extends AbstractNIOSelector
{
    protected Integer[] selectionKeys()
    {
        return new Integer[]{SelectionKey.OP_READ};
    }

    /**
     * 新可读请求
     * @param selectionKey
     */
    protected void process(SelectionKey selectionKey)
    {
        if (!selectionKey.isReadable()) return;

        SocketChannel chl = (SocketChannel) selectionKey.channel();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteBuffer buf = ByteBuffer.allocate(1024);
        int len = 0;

        boolean fail = false;
        try
        {
            while (0 < (len = chl.read(buf)))
                out.write(buf.array(), 0, len);
        } catch (IOException e)
        {
            e.printStackTrace();
            fail = true;
        }

        if (0 >= out.size() || fail)// 关闭连接
        {
            try
            {
                if (chl.isConnected())
                    chl.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
            return;
        }

        String str = new String(out.toByteArray());
        System.out.println("boss receive >> " + str);

        // 回写
        byte[] writeCtn = "hi".getBytes();
        ByteBuffer writeBuf = ByteBuffer.wrap(writeCtn);
        try
        {
            chl.write(writeBuf);
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
